package com.xpqh.ai.service;

import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.xpqh.ai.dto.CozeRequest;
import com.xpqh.ai.dto.CozeResponse;
import lombok.extern.slf4j.Slf4j;
import okhttp3.*;
import org.springframework.stereotype.Service;

import java.io.IOException;
import java.util.concurrent.TimeUnit;

/**
 * 扣子API服务类
 */
@Service
@Slf4j
public class CozeService {
    
    private static final String COZE_API_URL = "https://api.coze.cn/v1/workflow/stream_run";
    private static final String TOKEN = "pat_y9mZRkyJtGrWQvHCvLQMkW0fAbm9e9TH1e2hw7WRw9xotcEPTVbnelghEiH74gMZ";
    private static final String WORKFLOW_ID = "7520825626599014440";
    
    private final OkHttpClient httpClient;
    private final ObjectMapper objectMapper;
    
    public CozeService() {
        this.httpClient = new OkHttpClient.Builder()
                .connectTimeout(30, TimeUnit.SECONDS)
                .writeTimeout(30, TimeUnit.SECONDS)
                .readTimeout(60, TimeUnit.SECONDS)
                .build();
        this.objectMapper = new ObjectMapper();
    }
    
    /**
     * 调用扣子API进行图像处理
     * 
     * @param request 请求参数
     * @return 响应结果
     */
    public CozeResponse processImage(CozeRequest request) {
        long startTime = System.currentTimeMillis();
        
        try {
            // 构建请求体
            String requestBody = buildRequestBody(request);
            log.info("扣子API请求体: {}", requestBody);
            
            // 创建HTTP请求
            Request httpRequest = new Request.Builder()
                    .url(COZE_API_URL)
                    .post(RequestBody.create(requestBody, MediaType.get("application/json")))
                    .addHeader("Authorization", "Bearer " + TOKEN)
                    .addHeader("Content-Type", "application/json")
                    .addHeader("Accept", "text/event-stream")
                    .build();
            
            // 执行请求
            try (Response response = httpClient.newCall(httpRequest).execute()) {
                if (!response.isSuccessful()) {
                    String errorBody = response.body() != null ? response.body().string() : "Unknown error";
                    log.error("扣子API调用失败，状态码: {}, 错误信息: {}", response.code(), errorBody);
                    return CozeResponse.error("API调用失败，状态码: " + response.code() + ", 错误: " + errorBody);
                }
                
                // 处理流式响应
                String responseBody = response.body().string();
                log.info("扣子API原始响应: {}", responseBody);
                
                // 解析流式响应
                CozeResponse cozeResponse = parseStreamResponse(responseBody);
                
                long processingTime = System.currentTimeMillis() - startTime;
                log.info("扣子API调用成功，耗时: {}ms", processingTime);
                
                return cozeResponse;
                
            }
        } catch (Exception e) {
            log.error("扣子API调用异常", e);
            return CozeResponse.error("调用扣子API失败: " + e.getMessage());
        }
    }
    
    /**
     * 构建请求体
     */
    private String buildRequestBody(CozeRequest request) throws IOException {
        // 构建请求参数
        JsonNode requestJson = objectMapper.createObjectNode()
                .put("workflow_id", WORKFLOW_ID)
                .set("parameters", objectMapper.createObjectNode()
                        .put("image_url", request.getImage_url())
                        .put("prompt", request.getPrompt()));
        
        return objectMapper.writeValueAsString(requestJson);
    }
    
    /**
     * 解析流式响应
     */
    private CozeResponse parseStreamResponse(String responseBody) {
        try {
            // 处理Server-Sent Events格式的响应
            String[] lines = responseBody.split("\n");
            CozeResponse finalResponse = null;
            
            for (String line : lines) {
                if (line.startsWith("data: ")) {
                    String jsonData = line.substring(6).trim();
                    if (jsonData.equals("[DONE]")) {
                        break;
                    }
                    
                    try {
                        JsonNode dataNode = objectMapper.readTree(jsonData);
                        CozeResponse response = objectMapper.treeToValue(dataNode, CozeResponse.class);
                        
                        // 如果是结束节点，保存最终响应
                        if (Boolean.TRUE.equals(response.getNode_is_finish()) && 
                            "End".equals(response.getNode_type())) {
                            finalResponse = response;
                            
                            // 解析content中的JSON数据
                            if (response.getContent() != null) {
                                try {
                                    JsonNode contentNode = objectMapper.readTree(response.getContent());
                                    CozeResponse.ContentData contentData = objectMapper.treeToValue(contentNode, CozeResponse.ContentData.class);
                                    response.setContentData(contentData);
                                } catch (Exception e) {
                                    log.warn("解析content JSON失败: {}", e.getMessage());
                                }
                            }
                        }
                    } catch (Exception e) {
                        log.warn("解析响应行失败: {}, 行内容: {}", e.getMessage(), jsonData);
                    }
                }
            }
            
            return finalResponse != null ? finalResponse : CozeResponse.error("未找到有效的响应数据");
            
        } catch (Exception e) {
            log.error("解析流式响应失败", e);
            return CozeResponse.error("解析响应失败: " + e.getMessage());
        }
    }
} 